/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.videodes.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * This class is for the xml schema validating.
 * 
 * @author vaclav
 */
public class XMLValidation {
    
    private static final Logger LOGGER = Logger.getLogger(XMLValidation.class.getName());
    
    /**
     * Executes the XML Schema validation.
     * 
     * @param xml the xml that is being validated.
     * @param schemaClassPath classpath location of the schema (e.g. cz/muni/fi/pb153/videodes/file/schema.xsd).
     */
    public static boolean validate(String xml, String schemaClassPath) {
        InputStream streamSchema = null;
        try {
            SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
            
            streamSchema = XMLValidation.class.getClassLoader().getResourceAsStream(schemaClassPath);
            InputSource is = new InputSource(streamSchema);
            Source schemaSource = new SAXSource(is);
            Schema schema = factory.newSchema(schemaSource);

            Validator validator = schema.newValidator();
            
            InputSource is2 = new InputSource(new StringReader(xml));
            Source source = new SAXSource(is2);
            
            validator.validate(source);
            return true;
        } catch (SAXException ex) {
            LOGGER.log(Level.SEVERE, "The schema either couldn't be loaded or the xml is not valid. ", ex);
            return false;
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, "IO excption. ", ex);
            return false;
        } finally {
            if (streamSchema != null) {
                try {
                    streamSchema.close();
                } catch (IOException ex) {
                    LOGGER.log(Level.SEVERE, "An error has occured when closing an input stream. ", ex);
                }
            }
        }
    }
}
